package com.modulemanager.views

import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.WindowManager
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.libbase.Weak
import com.libmodulemanager.R
import com.libservice.RouteResult
import com.libservice.ServiceManager
import com.libservice.screenshotservice.ScreenshotListener
import com.libui.BaseActivity
import com.libui.utils.WindowUtils
import com.modulemanager.ModuleManager
import com.modulemanager.page.PageInterface
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.lang.ref.WeakReference

open class PageActivity : ScreenshotListener, BaseActivity() {
    companion object {
        private const val TAG_PAGE_FRAGMENT: String = "tag_page_fragment"
    }

    var page: PageInterface? by Weak()

    private var fragment: Fragment? = null

    private var exitTime: Long = 0

    override fun onResume() {
        super.onResume()

//        CoroutineScope(Dispatchers.IO).launch {
//            ServiceManager.instance.screenShotService.screenshotListener = this@PageActivity
//            ServiceManager.instance.screenShotService.startListen(WeakReference(this@PageActivity))
//        }
    }

    override fun onPause() {
        super.onPause()

//        CoroutineScope(Dispatchers.IO).launch {
//            ServiceManager.instance.screenShotService.stopListen(WeakReference(this@PageActivity))
//            ServiceManager.instance.screenShotService.screenshotListener = null
//        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        val moduleType: String = intent.getStringExtra("moduleType") ?: return
        val moduleId: String? = intent.getStringExtra("moduleId")
        val pageType: String = intent.getStringExtra("pageType") ?: return
        val pageId: String? = intent.getStringExtra("pageId")

        val page: PageInterface = ModuleManager.instance.page(
            moduleType, moduleId, pageType, pageId, null
        ) ?: return

        this.page = page

        super.onCreate(savedInstanceState)

        onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                ServiceManager.instance.routerService.pop(
                    delta = page.popDelta,
                    value = page.completionParam,
                    animated = true,
                )
            }
        })

        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)

        setContentView(R.layout.activity_page)

        val fragmentManager: FragmentManager = supportFragmentManager
        fragment = fragmentManager.findFragmentByTag(TAG_PAGE_FRAGMENT)
        if (fragment == null) {
            page.context = this

            val fragment: Fragment = page.fragmentContainer.fragment
            this.fragment = fragment

            fragmentManager.beginTransaction()
                .add(R.id.fragment_container, fragment, TAG_PAGE_FRAGMENT).commit()
        }
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()

        if (fragment is PageFragment) {
            (fragment as PageFragment).content.setPadding(
                0, 0, 0, WindowUtils.instance.getNavigationBarHeight(this)
            )
        }
    }

    @Suppress("DEPRECATION")
    @Deprecated("Deprecated in Java", ReplaceWith("registerForActivityResult"))
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        fragment?.onActivityResult(requestCode, resultCode, data)
    }

    override fun onDestroy() {
        page?.completion?.let { it(RouteResult.SUCCESS, page?.completionParam) }

        super.onDestroy()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK
            && event?.action == KeyEvent.ACTION_DOWN
            && ServiceManager.instance.activityService.activities.count() == 1
        ) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(applicationContext, "再按一次返回键退出程序", Toast.LENGTH_SHORT)
                    .show()
                exitTime = System.currentTimeMillis()
            } else {
                moveTaskToBack(false)
            }
            return true
        }

        return super.onKeyDown(keyCode, event)
    }

    override fun onShot(imagePath: String?) {
        ServiceManager.instance.routerService.push("app://page/system/feedback", false)
    }
}